package com.zhaoxi.project.fms.service.impl;

import com.zhaoxi.common.utils.Arith;
import com.zhaoxi.common.utils.DateUtils;
import com.zhaoxi.framework.web.server.BaseServiceImpl;
import com.zhaoxi.project.fms.domain.FmsAccount;
import com.zhaoxi.project.fms.domain.FmsBill;
import com.zhaoxi.project.fms.mapper.FmsAccountMapper;
import com.zhaoxi.project.fms.mapper.FmsBillMapper;
import com.zhaoxi.project.wms.domain.WmsOrderLine;
import com.zhaoxi.project.wms.mapper.WmsOrderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 财务单据Service业务层处理
 *
 * @author zhaoxi
 * @date 2023-08-14
 */
@Service
public class FmsBillServiceImpl extends BaseServiceImpl {
    @Autowired
    private FmsBillMapper fmsBillMapper;
    @Autowired
    private WmsOrderMapper wmsOrderMapper;
    @Autowired
    private FmsAccountServiceImpl fmsAccountService;

    public List<FmsBill> modifyFmsBill(FmsBill fmsBill) {
        String type = fmsBill.getType();
        List<FmsBill> result = new ArrayList<>();// 创建结果列表
        if ("1".equals(type)) {
            // 进行修改，例如：
            fmsBill.setType("收款");  // 修改类型为 "收款"
            result = fmsBillMapper.selectFmsBillList(fmsBill);
            return result;
        }
        return fmsBillMapper.selectFmsBillList(fmsBill);
    }

    /**
     * 查询财务单据
     *
     * @param id 财务单据主键
     * @return 财务单据
     */

    public FmsBill selectFmsBillById(Long id) {
        return fmsBillMapper.selectFmsBillById(id);
    }

    /**
     * 查询财务单据列表
     *
     * @param fmsBill 财务单据
     * @return 财务单据
     */
    public List<FmsBill> selectFmsBillList(FmsBill fmsBill) {
//        String type = fmsBill.getType();
//        List<FmsBill> result = new ArrayList<>();// 创建结果列表
//        // 1 是收款单type ,
//        if ("1".equals(type)) {
//            fmsBill.setType("收款");  // 修改类型为 "收款"
//            //拿到fms_bill列表数据
//            result = fmsBillMapper.selectFmsBillList(fmsBill);
//            //拿到wms_order_line表数据
//            List<WmsOrderLine> list = wmsOrderMapper.getOrderLine1();
//            //页面上显示每个fms_bill列表数据的(id),(order_id)
//            // 为wms_order_line的id,(goods_code)数据
//            for (FmsBill fmsBillitem : result) {
//                for (WmsOrderLine wmsOrderLineitem : list) {
//                    Long wmsOrderLineitemID = wmsOrderLineitem.getId();
//                    String OrderId = wmsOrderLineitemID.toString();
//                    if (fmsBillitem.getOrderId().equals(OrderId)) {
//                        fmsBillitem.setId(wmsOrderLineitem.getId());
//                        fmsBillitem.setOrderId(wmsOrderLineitem.getGoodsCode());
//                    }
//                }
//            }
//            //直接返回修改后的fms_bill数据，如果没有页面type组件直接返回原始数据，例如（财务单据页面）
//            return result;
//        }
        fmsBill.setTenantId(this.getTenantId());
        return fmsBillMapper.selectFmsBillList(fmsBill);
    }

    /**
     * 新增财务单据
     *
     * @param fmsBill 财务单据
     * @return 结果
     */

    public int insertFmsBill(FmsBill fmsBill) {
//        //收款单页面新增，前端传过来的数据有wms_order_line表，fms_account表，
//        // fms_account_log表，fms_bill
//        fmsBill.setCreateTime(DateUtils.getNowDate());
//        WmsOrderLine wmsOrderLineInster = new WmsOrderLine();
//        //wms_order_line表新增
//        wmsOrderLineInster.setGoodsCode(fmsBill.getOrderId());
//        wmsOrderLineInster.setTotalMoney(fmsBill.getTotalMoney());
//        wmsOrderLineInster.setReceivableMoney(fmsBill.getReceivableMoney());
//        wmsOrderLineInster.setMoney(fmsBill.getMoney());
//        wmsOrderLineInster.setBatchCode(fmsBill.getOrderId());
//        wmsOrderLineInster.setQuantity(fmsBill.getQuantity());
//        wmsOrderMapper.insertWmsOrderLine(wmsOrderLineInster);
//        //fms_account账户金额更新
//        Long accountId = fmsBill.getAccountId();
//        BigDecimal accountMoney = fmsBill.getMoney();
//        FmsAccount account = accountMapper.selectFmsAccountById(accountId);
//        BigDecimal currentAmount = account.getCurrentAmount();
//        BigDecimal insertCurrentAmount = currentAmount.add(accountMoney);
//        account.setCurrentAmount(insertCurrentAmount);
//        accountMapper.updateFmsAccount(account);
//        //fms_account_log表账户金额新增
//        accountMapper.insertFmsAccountLog(accountId);
//        //fms_bill表新增
//        String type = fmsBill.getType();
//        if (type.equals("1")) {
//            fmsBill.setType("收款");
//            //WmsOrderLine wmsOrderLine = new WmsOrderLine();
//            String orderIdStr = fmsBill.getOrderId();
//            //wms_order_line表中有很多goods——code相同的订单，但是上面刚插入的在最后
//            //下面for循环拿到的也是最后一个
//            List<WmsOrderLine> orderLineById = wmsOrderMapper.getOrderLineByGoodsCode(orderIdStr);
//            for (WmsOrderLine wmsOrderLine : orderLineById) {
//                Long id = wmsOrderLine.getId();
//                String idStr = Long.toString(id);
//                fmsBill.setOrderId(idStr);
//            }
//        }
        fmsBill.setState("1");//未审核
        fmsBill.setUserId(this.getUserId());
        fmsBill.setCreateTime(DateUtils.getNowDate());
        fmsBill.setCreateBy(this.getUsername());
        fmsBill.setUpdateTime(DateUtils.getNowDate());
        fmsBill.setUpdateBy(this.getUsername());
        fmsBill.setTenantId(this.getTenantId());
        //如果只有一期，插入后，直接返回就好了
        if (!(fmsBill.getByStages()>1) ){
            return fmsBillMapper.insertFmsBill(fmsBill);
        }
        Double receivableMoney = fmsBill.getReceivableMoney();
        Double receivableMoney1 = Arith.div(receivableMoney,fmsBill.getByStages(),2);
        Double receivableMoney2 = fmsBill.getReceivableMoney();
        Double double1;
        int i = 1;
        while (true) {
            if (Arith.mul(receivableMoney1,i) >= receivableMoney) {
                double1 = receivableMoney2;
                receivableMoney2 = receivableMoney2 - double1;
            }else{
                double1 = receivableMoney1;
                receivableMoney2 = receivableMoney2 - double1;
            }
            fmsBill.setReceivableMoney(double1);

            if (double1 > 0){
                fmsBillMapper.insertFmsBill(fmsBill);
                //每期一个月
                fmsBill.setPlanTime(DateUtils.addMonths(fmsBill.getPlanTime(),1));
            }else{
                break;
            }
            i ++;
        }
        return i - 1;
    }

    /**
     * 修改财务单据
     *
     * @param updatedBill 财务单据
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public int updateFmsBill(FmsBill updatedBill) {
        updatedBill.setUpdateTime(DateUtils.getNowDate());
        System.out.println("123456" + updatedBill);


        // 查询原始的FmsBill数据
        FmsBill originalBill = fmsBillMapper.selectFmsBillById(updatedBill.getId());
        System.out.println("originalBill===>" + originalBill);
        System.out.println("updatedBill====>" + updatedBill);
        //更新wms_order_line表数据
        String updataOrderIdStr = originalBill.getOrderId();
        Long updataOrderIdLong = Long.parseLong(updataOrderIdStr);
//        WmsOrderLine updataWmsOrderLine = wmsOrderMapper.getOrderLineById(updataOrderIdLong);
//        System.out.println("updataWmsOrderLine" + updataWmsOrderLine);
//        updataWmsOrderLine.setMoney(updatedBill.getMoney());
//        updataWmsOrderLine.setTotalMoney(updatedBill.getTotalMoney());
//        updataWmsOrderLine.setReceivableMoney(updatedBill.getReceivableMoney());
//        wmsOrderMapper.updataWmsOrderLine(updataWmsOrderLine);
////更新fms_account账户金额
//        // 计算金额差
//        BigDecimal moneyDifference = originalBill.getMoney().subtract(updatedBill.getMoney());
        // 更新FmsBill表中的totalMoney、receivableMoney、money字段
        int rowsAffected = fmsBillMapper.updateFmsBill(updatedBill);
        if (rowsAffected <= 0) {
            throw new RuntimeException("更新FmsBill表失败");
        }
        // 更新Account表中的money字段
        FmsAccount account = fmsAccountService.selectFmsAccountById(updatedBill.getAccountId());
        if (account == null) {
            throw new RuntimeException("未找到相关账户");
        }
//        BigDecimal updatedMoney = account.getCurrentAmount().subtract(moneyDifference);
//        if (updatedMoney.compareTo(BigDecimal.ZERO) < 0) {
//            throw new RuntimeException("账户余额不足");
//        }
//        account.setCurrentAmount(updatedMoney);
        rowsAffected = fmsAccountService.updateFmsAccount(account);
        if (rowsAffected <= 0) {
            throw new RuntimeException("更新Account表失败");
        }
        /*Long accountId = fmsBill.getAccountId();
        BigDecimal accountMoney = fmsBill.getMoney();
        FmsAccount account=accountMapper.selectFmsAccountById(accountId);
        BigDecimal currentAmount = account.getCurrentAmount();
        BigDecimal insertCurrentAmount = currentAmount.add(accountMoney);
        account.setCurrentAmount(insertCurrentAmount);
        accountMapper.updateFmsAccount(account);*/

//更新fms_bill表
        updatedBill.setOrderId(originalBill.getOrderId());
//新增fms_account_log表
//        fmsAccountService.insertFmsAccountLog(updatedBill.getAccountId());
        return fmsBillMapper.updateFmsBill(updatedBill);
    }

    /**
     * 批量删除财务单据
     *
     * @param ids 需要删除的财务单据主键
     * @return 结果
     */

    public int deleteFmsBillByIds(Long[] ids) {
        return fmsBillMapper.deleteFmsBillByIds(ids);
    }

    /**
     * 删除财务单据信息
     *
     * @param id 财务单据主键
     * @return 结果
     */

    public int deleteFmsBillById(Long id) {
        return fmsBillMapper.deleteFmsBillById(id);
    }

    public int auditFmsBill(FmsBill fmsBill) {
        FmsAccount account = fmsAccountService.selectFmsAccountById(fmsBill.getAccountId());
        if (account == null) {
            throw new RuntimeException("未找到相关账户");
        }
        if (fmsBill.getType().equals("1") || fmsBill.getType().equals("3")){
            account.setParams("money",fmsBill.getMoney());
        } else if (fmsBill.getType().equals("2") || fmsBill.getType().equals("4")){
            account.setParams("money",fmsBill.getMoney() * -1);
        } else if (fmsBill.getType().equals("5")){
            // 转账还没写好。
        }
        if (fmsAccountService.updateFmsAccountCurrentAmountById(account) > 0){
            fmsBill.setState("0");
            fmsBill.setUpdateBy(this.getUsername());
            fmsBill.setUpdateTime(DateUtils.getNowDate());
        }else{
            return -1;
        }

        return fmsBillMapper.updateFmsBill(fmsBill);
    }
}










